package com.zjh.admin.app.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjh.admin.app.model.AppUserEntity;
import com.zjh.admin.app.model.CommentEntity;
import com.zjh.admin.app.model.VideoEntity;
import com.zjh.admin.app.service.AppUserService;
import com.zjh.admin.app.service.CommentService;
import com.zjh.common.constants.Common;
import com.zjh.common.dtgrid.model.Pager;
import com.zjh.common.dtgrid.util.ExportUtils;
import com.zjh.common.result.Result;
import com.zjh.common.util.PageUtil;
import com.zjh.core.base.basecontroller.BaseController;
import com.zjh.core.exception.AjaxException;
import com.zjh.core.exception.SystemException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author WYX
 * @Description controller
 * @Date 2019/11/17 18:00
 */
@Controller
@RequestMapping("/comment/")
public class CommentController extends BaseController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private AppUserService appUserService;

    /**
     * list跳转
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("listUI.html")
    public String listUI(Model model, HttpServletRequest request) {
        try {
            PageUtil page = new PageUtil();
            if (request.getParameterMap().containsKey("page")) {
                setPage(request, page);
            }
            model.addAttribute("page", page);
            return Common.BACKGROUND_PATH + "/app/comment/list";
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * ajax分页查询评论
     *
     * @param gridPager
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "list.html")
    @ResponseBody
    public Object list(String gridPager, HttpServletResponse response) throws Exception {
        // 映射Pager对象
        Pager pager = JSON.parseObject(gridPager, Pager.class);
        // 判断是否包含自定义参数
        Map<String, Object> parameters = pager.getParameters();
        parameters.put("fastQueryMap", getFastqueryParameters(pager.getFastQueryParameters()));
        //3、判断是否是导出操作
        if (pager.getIsExport()) {
            if (pager.getExportAllData()) {
                //3.1、导出全部数据
                List<CommentEntity> list = commentService.queryListByPage(parameters);
                ExportUtils.exportAll(response, pager, list);
                return null;
            } else {
                //3.2、导出当前页数据
                ExportUtils.export(response, pager);
                return null;
            }
        } else {
            //设置分页，page里面包含了分页信息
            Page<Object> page = PageHelper.startPage(pager.getNowPage(), pager.getPageSize(), true);
            List<CommentEntity> list = commentService.queryListByPage(parameters);



            parameters.clear();
            setPageList(parameters, pager, page, list);
            return parameters;
        }
    }

    /**
     * 评论
     *
     * @param comment
     * @return
     */
    @RequestMapping("add.html")
    @ResponseBody
    public Object add(String comment, MultipartFile[] files, HttpServletRequest request) {
        if (StringUtils.isEmpty(comment)) return null;
        CommentEntity commentEntity = JSON.parseObject(comment, CommentEntity.class);
        Result result = new Result();
        try {
            if (files != null)
                for (MultipartFile file : files) {
                    saveFile(file, request, result, "comment");
                }
            int status = commentService.insert(commentEntity);
            if (status > 0) {
                result.setData(commentEntity.getId());
                result.success("添加成功");
            } else {
                result.error("添加失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    private String saveFile(MultipartFile multipartFile, HttpServletRequest request, Result<Map> result, String type) throws IOException {
        String path;
        String fileName = multipartFile.getOriginalFilename();
//        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String fileRealPath = request.getSession().getServletContext().getRealPath("/") + Common.UPLOAD_IMAGE_PATH + "/" + type + "/";
        //自定义图片上传位置,这里是上传到项目的upload下，需要手动刷新下upload文件夹页面才能显示，如果存放在服务器的话
        //每次重启服务器图片都会消失
        String webPath = Common.UPLOAD_IMAGE_PATH + "/" + type + "/";

//        String tempName = UUID.randomUUID().toString();

        //判断文件夹是否存在
        File targerFile = new File(fileRealPath);
        if (!targerFile.exists()) {
            targerFile.mkdirs();
        }
        //保存文件
        File uploadFile = new File(fileRealPath + fileName);
        FileCopyUtils.copy(multipartFile.getBytes(), uploadFile);
        result.success("上传成功");
        return "";
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping("delete.html")
    @ResponseBody
    public Object delete(String ids) {
        Result result = new Result();
        try {
            int flag = commentService.deleteById(Long.valueOf(ids));
            if (flag > 0) {
                result.success("删除成功");
            } else {
                result.error("删除失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "listByVideo.html")
    @ResponseBody
    public Object queryListByVideo(int vId, HttpServletResponse response) throws Exception {
        Result result = new Result();
        List<CommentEntity> list = commentService.queryListByVideo(vId);
        for (CommentEntity commentEntity : list) {
            if (commentEntity.getReplyId() > 0){
                AppUserEntity appUserEntity = appUserService.findById(Long.valueOf(commentEntity.getReplyId()));
                commentEntity.setUserName(appUserEntity.getuName());
            }
        }
        if (list != null) {
            result.success();
            result.setData(list);
        } else result.error();

        return result;
    }

    @PostMapping(value = "listByUser.html")
    @ResponseBody
    public Object queryListByUser(int uId, HttpServletResponse response) throws Exception {
        Result result = new Result();
        List<CommentEntity> list = commentService.queryListByUser(uId);
        if (list != null) {
            result.success();
            result.setData(list);
        } else result.error();

        return result;
    }

    /**
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "countComment.html")
    @ResponseBody
    public Object countComment(int uId, HttpServletResponse response) throws Exception {
        return commentService.countCommentByUid(uId);
    }

}
